package org.spiderflow.oss.executor.shape;

import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.spiderflow.ExpressionEngine;
import org.spiderflow.context.SpiderContext;
import org.spiderflow.executor.ShapeExecutor;
import org.spiderflow.model.Shape;
import org.spiderflow.model.SpiderNode;
import org.spiderflow.oss.model.Oss;
import org.spiderflow.oss.model.OssFile;
import org.spiderflow.oss.utils.OSSUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class OssOperationExecutor implements ShapeExecutor{
	
	public static final String OSS_ID = "ossId";
	
	public static final String BYTES = "bytes";
	
	public static final String FILE_NAME = "fileName";
	
	public static final String FILE_PATH = "filePath";
	
	public static final String OPERATION_TYPE = "operationType";
	
	public static final String OPERATION_TYPE_PUT = "ossPut";
	
	public static final String OPERATION_TYPE_DELETE = "ossDelete";
	
	public static final String VARIABLE_NAME = "variableName";
	
	@Autowired
	private ExpressionEngine engine;
	
	@Override
	public String supportShape() {
		return "ossOperation";
	}
	
	@Override
	public Shape shape() {
		Shape shape = new Shape();
		shape.setImage("");
		shape.setLabel("OSS操作");
		shape.setName("ossOperation");
		shape.setTitle("OSS操作");
		return shape;
	}

	@Override
	public void execute(SpiderNode node, SpiderContext context, Map<String, Object> variables) {
		String ossId = node.getStringJsonValue(OSS_ID);
		Oss oss = (Oss) context.get(OssExecutor.OSS_CONTEXT_KEY + ossId);
		if(!StringUtils.isNotBlank(ossId)){
			context.debug("请选择OSS！");
		}else {
			String operationType = node.getStringJsonValue(OPERATION_TYPE);
			if(operationType.equals(OPERATION_TYPE_PUT)) {
				String bytes = node.getStringJsonValue(BYTES);
				String fileName = node.getStringJsonValue(FILE_NAME);
				Object bytesResult = engine.execute(bytes, variables);
				Object fileNameResult = engine.execute(fileName, variables);
				OssFile ossFile = OSSUtil.uploadFileToOss(oss, (byte[]) bytesResult, (String) fileNameResult, context);
				variables.put(node.getStringJsonValue(VARIABLE_NAME),ossFile);
			}else if(operationType.equals(OPERATION_TYPE_DELETE)){
				String filePath = node.getStringJsonValue(FILE_PATH);
				Object filePathResult = engine.execute(filePath, variables);
				if(filePathResult == null) {
					filePathResult = filePath;
				}
				OSSUtil.deleteFile(oss, (String) filePathResult, context);
			}
		}
	}
	
}
